<template>
  <div class="page-container">
    <div class="map-wrapper">
      <div class="title-wrapper">
        <span class="time">时间范围</span>
        <div class="title flex">
          <i-range-picker
            style="width: 25%; margin: 0 12px 20px 0"
            show-time
            :time-picker-props="{ defaultValue: ['00:00:00', '23:59:59'] }"
            format="YYYY-MM-DD HH:mm:ss"
            @change="onChangeFn"
            v-model="timeRange"
          />
          <a-button type="primary" @click="handleSearch">查看行驶轨迹</a-button>
        </div>
      </div>
      <div class="bottom" v-if="list.length">
        <div id="carGpsTrailMap" class="map">
          <div class="msg">
            <div class="msg-car">车辆【{{ record.licenseNo || '-' }}】的轨迹</div>
            <div class="msg-car">位置信息最后更新时间：{{ lastGPS.gpsLastPointTime || '-' }}</div>
          </div>
        </div>
        <div class="play-block">
          <!-- 暂停 -->
          <img v-if="playStatus == 1" src="@/assets/icons/stop.png" @click="handlePause" />
          <img v-else src="@/assets/icons/play.png" @click="handleStartBtn" />

          <div class="speed-block">
            <div class="speed-btn" @click="reset"> <icon-sync /> 重置 </div>
            <div class="speed-btn" :class="{ 'is-actived': playSpeed == 1 }" @click="handleSpeed(1)"> 1.0X </div>
            <div class="speed-btn" :class="{ 'is-actived': playSpeed == 2 }" @click="handleSpeed(2)"> 10.0X </div>
            <div class="speed-btn" :class="{ 'is-actived': playSpeed == 3 }" @click="handleSpeed(3)"> 50.0X </div>
          </div>
        </div>
      </div>
      <div v-else class="empty-block"><a-empty /></div>
    </div>
  </div>
</template>

<script>
  import { loadMapScript } from '@/utils/loadMap'
  import { getCarTboxVehicleDetail, getCarGpsTrail, getByCarIdDetail } from '@/api/asset/carTbox'
  import { vehicleGPS } from '@/api/asset/vehicle'
  import dayjs from 'dayjs'

  import carImg from '@/assets/icons/car.png'
  import qiImg from '@/assets/icons/qi.png'
  import zhiImg from '@/assets/icons/zhi.png'
  const SPEED_CONFIG = [500, 50, 10]

  export default {
    name: 'CarBoxUseTrack',

    data() {
      return {
        timeRange: undefined,
        list: [],
        // 0 未开始,从头播放 1 已经开始 2暂停,继续播放
        playStatus: 0,
        // 1,2,3 速度
        playSpeed: 1,
        lastGPS: {},
        record: {},
        page: '',
      }
    },
    mounted() {
      this.page = this.$route.query && this.$route.query.page
      const id = this.$route.params.id
      console.log('this.$route.query', this.$route.query)
      console.log('this.$route.params', this.$route.params)
      this.getDetail(id)
    },
    methods: {
      getDetail(id) {
        let fetch = getCarTboxVehicleDetail
        if (this.page) {
          fetch = getByCarIdDetail
        }
        fetch({ id: id }).then((res) => {
          this.record = res.result
          this.getLastGPS()
        })
      },
      initMap() {
        this.polyfillNewMap({}, 'carGpsTrailMap')
        // 工具
        this.polyfillAddToolBar()
      },
      // 初始化轨迹，分发
      initCarTrail() {
        // 加载地图
        loadMapScript().then(() => {
          this.initMap()
          this.initCarTrailAMap()
        })
      },
      initCarTrailAMap() {
        const lnglatList = this.list.map((item) => item.lnglat)

        AMap.plugin('AMap.MoveAnimation', () => {
          const carIcon = new AMap.Icon({
            image: carImg,
            size: new AMap.Size(33, 33),
            imageSize: new AMap.Size(15, 33),
            // 图标取图偏移量
            imageOffset: new AMap.Pixel(0, 0),
          })
          const qiIcon = new AMap.Icon({
            image: qiImg,
            size: new AMap.Size(20, 20),
            imageSize: new AMap.Size(20, 20),
            // 图标取图偏移量
            imageOffset: new AMap.Pixel(0, 0),
          })
          const zhiIcon = new AMap.Icon({
            image: zhiImg,
            size: new AMap.Size(22, 27),
            imageSize: new AMap.Size(22, 27),
            // 图标取图偏移量
            imageOffset: new AMap.Pixel(0, 0),
          })

          // 车辆
          this.animationMarker = new AMap.Marker({
            map: this.map,
            position: lnglatList[0],
            icon: carIcon,
            size: new AMap.Size(15, 33),
            offset: new AMap.Pixel(0, 0),
          })
          // 起
          new AMap.Marker({
            map: this.map,
            position: lnglatList[0],
            zIndex: 10,
            icon: qiIcon,
          })
          new AMap.Marker({
            map: this.map,
            position: lnglatList.at(-1),
            zIndex: 10,
            icon: zhiIcon,
          })

          // 绘制轨迹
          new AMap.Polyline({
            map: this.map,
            path: lnglatList,
            showDir: true,
            strokeColor: '#CACACA', //线颜色
            strokeOpacity: 1, //线透明度
            strokeWeight: 6, //线宽
            strokeStyle: 'solid', //线样式
          })
          // 运动line
          const passedPolyline = new AMap.Polyline({
            map: this.map,
            strokeColor: '#3D80FF', //线颜色
            strokeWeight: 6, //线宽
            strokeOpacity: 1, //线透明度
            showDir: true,
          })
          this.animationMarker.on('moving', function (e) {
            passedPolyline.setPath(e.passedPath)
          })
          this.animationMarker.on('moveend', (e) => {
            if (e.index == lnglatList.length - 1) {
              this.playStatus = 0
            }
          })
          this.map.setFitView()
        })
      },

      handleSearch() {
        if (this.timeRange && this.timeRange.length) {
          this.getCarTrailDetail()
        } else {
          this.$message.warning('请先选择时间后查看行驶轨迹')
        }
      },
      // 获取车辆轨迹详情
      async getCarTrailDetail() {
        const queryData = {
          vehicleNum: this.record.vehicleSn,
          startTime: this.timeRange[0],
          endTime: this.timeRange[1],
        }
        const res = await getCarGpsTrail(queryData)
        if (res.code == 200) {
          this.list = res.result.map((item) => {
            return {
              direction: item.direction,
              lnglat: [item.longitudeGcj, item.latitudeGcj],
            }
          })
          if (this.list.length) {
            this.initCarTrail()
          }
        }
      },
      // 开始
      handleStart() {
        if (this.list && this.list.length > 1) {
          const duration = SPEED_CONFIG[this.playSpeed - 1]
          const lnglatList = this.list.map((item) => item.lnglat)
          this.animationMarker.moveAlong(lnglatList, {
            // 每一段的时长
            duration, //可根据实际采集时间间隔设置
            // JSAPI2.0 是否延道路自动设置角度在 moveAlong 里设置
            autoRotation: true,
          })
          this.playStatus = 1
        }
      },
      // 暂停
      handlePause() {
        this.playStatus = 2
        this.animationMarker.pauseMove()
      },
      // 继续
      handleContinue() {
        this.animationMarker.resumeMove()
      },
      // 结束
      handleEnd() {
        this.animationMarker.stopMove()
      },
      // 开始按钮
      handleStartBtn() {
        if (this.playStatus == 0) {
          this.handleStart()
        } else {
          this.handleContinue()
        }
        this.playStatus = 1
      },
      // 切换速度
      handleSpeed(speed) {
        this.playSpeed = speed
        this.handleStart()
      },
      // 获取最后一次GPS
      async getLastGPS() {
        const res = await vehicleGPS({
          vehicleNum: this.record.vehicleSn,
        })
        const { result } = res
        if (res.code == 200 && result) {
          this.lastGPS = {
            gpsLastAddress: '',
            gpsLastPointTime: result.locationTime,
            longitudeGcj: result.longitudeGcj,
            latitudeGcj: result.latitudeGcj,
          }
          if (this.page) {
            // 订单工单跳转到轨迹
            // 跳转到轨迹页的时候，要带着车牌号进入。如果是换车工单会涉及到2台车，则使用换上车进行轨迹查询，如果换上车没安装车载box则不会展示轨迹查看按钮
            // 转到轨迹的时候，默认使用工单的实际开始时间、实际结束时间，将这2个值带进去
            // 如果工单还没开始执行，既没有实际开始时间也没有实际结束时间，或者只有实际开始时间没有实际结束时间，则依然进行页面跳转，但是带不进去的时间，默认为空
            if (this.$route.query.startTime != 'null' && this.$route.query.endTime != 'null') {
              this.timeRange = [this.$route.query.startTime, this.$route.query.endTime]
              this.getCarTrailDetail()
            }
          } else {
            // 默认结束时间就是“最晚一条该车gps”数据的时间，默认开始时间就是结束时间的8小时前
            this.timeRange = [
              dayjs(result.locationTime).subtract(8, 'hours').format('YYYY-MM-DD HH:mm:ss'),
              dayjs(result.locationTime).format('YYYY-MM-DD HH:mm:ss'),
            ]
            this.handleSearch()
          }
          // this.getCarPlace()
        }
      },
      // 逆地理编码
      getCarPlace() {
        loadMapScript().then(() => {
          const cpoint = [this.lastGPS.longitudeGcj, this.lastGPS.latitudeGcj] //中心点坐标
          this.polyfillGeocoderGetLocation(cpoint, (address) => {
            this.lastGPS.gpsLastAddress = address
          })
        })
      },

      onChangeFn(date) {
        if (date && date.length) {
          this.timeRange = date
        }
      },

      polyfillNewMap(config = {}, containerId = 'mapContainer') {
        console.log('MapLoad--load newMap')
        const { center = [116.397428, 39.90923], zoom = 16 } = config
        this.map = new AMap.Map(containerId, {
          center,
          zoom,
          ...config,
        })
      },
      // 逆地址解析
      polyfillGeocoderGetLocation(lnglat, callback) {
        const geocoder = new AMap.Geocoder({
          // city: "010", //城市设为北京，默认：“全国”
          // radius: 1000 //范围，默认：500
        })
        const point = new AMap.LngLat(...lnglat)
        geocoder.getAddress(point, (status, result) => {
          let address
          if (status === 'complete' && result.regeocode) {
            address = result.regeocode.formattedAddress
          } else {
            console.log('根据经纬度查询地址失败')
          }
          callback(address, result.regeocode)
        })
      },
      // 增加工具条
      polyfillAddToolBar(offset = [10, 10]) {
        this.map.addControl(
          new AMap.ToolBar({
            position: 'RB',
            offset,
          })
        )
      },
      reset() {
        this.playStatus = 0
        this.playSpeed = 1
        this.animationMarker.stopMove()
        this.initCarTrail()
      },
    },
  }
</script>

<style lang="less" scoped>
  .page-container {
    padding: 20px;
    .map-wrapper {
      width: 100%;
      border-radius: 0px 0px 0px 0px;
      .title-wrapper {
        .time {
          display: inline-block;
          font-weight: 400;
          font-size: 14px;
          color: #1d2129;
          line-height: 22px;
          margin-bottom: 4px;
        }
      }
      .bottom {
        padding: 20px;
        border: 1px solid #e5e6eb;
        .map {
          position: relative;
          width: 100%;
          height: 591px;
          padding: 20px;
          .msg {
            position: absolute;
            top: 20px;
            left: 20px;
            z-index: 1;
            padding: 6px 10px 0 10px;
            background: #ffffff;
            box-shadow: 0px 0px 4px 0px rgba(0, 0, 0, 0.24);
            border-radius: 4px 4px 4px 4px;
            .msg-car {
              font-size: 12px;
              color: #1d2129;
              line-height: 22px;
              padding-bottom: 4px;
            }
          }
        }
        .play-block {
          display: flex;
          justify-content: space-between;
          align-content: center;
          margin: 0 auto;
          width: 100%;
          background: #2b2b2f;
          padding: 8px;

          img {
            cursor: pointer;
          }

          .speed-block {
            display: flex;
            align-items: center;
            font-size: 12px;
            font-weight: 400;
            color: #ffffff;

            .speed-btn {
              width: 42px;
              height: 24px;
              line-height: 25px;
              border-radius: 40px;
              margin-left: 8px;
              text-align: center;
              cursor: pointer;
              &.is-actived {
                background: #3d80ff;
              }
            }
          }
        }
      }
      .empty-block {
        position: absolute;
        top: 100px;
        bottom: 0;
        width: 100%;
        background: #fff;
        padding-top: 100px;
      }
    }
  }
</style>
